﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing.Printing;
//using Microsoft.Office.Interop.Word;

namespace ViewRidgeAssistant
{
    public partial class main : Form
    {

        private string _current_state;                               //Режим работы приложения
        private int _act_id;
        private int _act_id_customer;
        private int _act_id_work;
        private int _art_id_artist;
        private bool _search_act;

        public main()
        {
            InitializeComponent();
            this.gw.Hide();
            this._current_state = "NONE";
            this.UpdateTitle();

            this.Actions.Visible = Program.user_set._main_gui._show_actions_panel;
            this.bn.Visible = Program.user_set._main_gui._show_gridcontrol_panel;
            this.Tools.Visible = Program.user_set._main_gui._show_tables_panel;

            this.mi_actions_panel.Checked = Program.user_set._main_gui._show_actions_panel;
            this.mi_tables_panel.Checked = Program.user_set._main_gui._show_tables_panel;
            this.mi_gridcontrol_panel.Checked = Program.user_set._main_gui._show_gridcontrol_panel;

            this.DisablePanels();

        }

        //Активировать панели управления 
        private void EnablePanels()
        {
            bn.Enabled = true;
            Tools.Enabled = true;
            if (!(this._current_state == "NONE")) { Actions.Enabled = true; }
            p_search.Enabled = true;
            this.Update();
            this.mi_imp_db.Enabled = true;
            this.mi_reports.Enabled = true;
            this.mi_sales_works_list.Enabled = true;
            this.mi_sql_console.Enabled = true;

            switch (this._current_state)
            {
                case "CUSTOMER":
                break;

                case "ARTIST":
                break;

                case "WORK_VIEW":
                break;

                case "TRANS_VIEW":
                break;

                case "CustomerInterests":
                break;
            }

        }

        //Деактивировать панели управления
        private void DisablePanels()
        {
            bn.Enabled = false;
            Tools.Enabled = false;
            Actions.Enabled = false;
            p_search.Enabled = false;
            this.Update();
            this.mi_imp_db.Enabled = false;
            this.mi_reports.Enabled = false;
            this.mi_sales_works_list.Enabled = false;
            this.mi_sql_console.Enabled = false;
        }

        //Обновить заголовок окна
        private void UpdateTitle()
        {
            switch (this._current_state)
            {
                case "NONE":
                    this.Text = "View Ridge Assistant v1.0 beta";
                    break;
                case "CUSTOMER":
                    this.Text = "View Ridge Assistant v1.0 beta - Клиенты";
                    break;
                case "TRANS_VIEW":
                    this.Text = "View Ridge Assistant v1.0 beta - Транзакции";
                    break;
                case "ARTIST":
                    this.Text = "View Ridge Assistant v1.0 beta - Художники";
                    break;
                case "WORK_VIEW":
                    this.Text = "View Ridge Assistant v1.0 beta - Работы";
                    break;
                case "CustomerInterests":
                    this.Text = "View Ridge Assistant v1.0 beta - Интересы";
                    break;
            }
        }

        private void ToolClients_Click(object sender, EventArgs e)
        {
            this.load_data_table("CUSTOMER");
            this.b_commit.Enabled = true;
        }

        private void ToolArtists_Click(object sender, EventArgs e)
        {
            this.load_data_table("ARTIST");
            this.b_commit.Enabled = true;
        }

        private void ToolWorks_Click(object sender, EventArgs e)
        {
            this.load_data_table("WORK_VIEW");
        }

        private void ToolTransactions_Click(object sender, EventArgs e)
        {
            this.load_data_table("TRANS_VIEW");
        }

        private void ToolInterests_Click(object sender, EventArgs e)
        {
            this.load_data_table("CustomerInterests");
        }

        private void load_data_table(string state)
        {
            ArrayList fields;
            gw.Hide();
            this._current_state = state;
            this.EnablePanels();
            bs.DataSource = Program.data_module.get_data_table(this._current_state).Tables[state];
            switch (this._current_state)
            {
                case "CUSTOMER":
                //bs.DataSource = Program.data_module.get_data_table(this._current_state).DefaultView;
                fields = Program.user_set._customer_table_fields;
                this.b_action_add.Enabled = true;
                this.b_edit.Enabled = true;
                this.b_search.Enabled = true;
                bn.Enabled = true;
                gw.ReadOnly = false;
                this.bindingNavigatorAddNewItem.Enabled = true;
                this.bindingNavigatorDeleteItem.Enabled = true;
                this.b_commit.Enabled = true;
                break;
                case "ARTIST":
                //bs.DataSource = Program.data_module.get_data_table(this._current_state).DefaultView;
                fields = Program.user_set._artist_table_fields;
                this.b_action_add.Enabled = true;
                this.b_edit.Enabled = true;
                this.b_search.Enabled = true;
                bn.Enabled = true;
                gw.ReadOnly = false;
                this.bindingNavigatorAddNewItem.Enabled = true;
                this.bindingNavigatorDeleteItem.Enabled = true;
                this.b_commit.Enabled = true;
                break;
                case "WORK_VIEW":
                //bs.DataSource = Program.data_module.get_data_table(this._current_state).DefaultView;
                fields = Program.user_set._work_table_fields;
                this.b_action_add.Enabled = true;
                this.b_edit.Enabled = true;
                this.b_search.Enabled = true;
                bn.Enabled = true;
                gw.ReadOnly = true;
                this.bindingNavigatorAddNewItem.Enabled = false;
                this.bindingNavigatorDeleteItem.Enabled = false;
                this.b_commit.Enabled = false;
                break;
                case "TRANS_VIEW":
                //bs.DataSource = Program.data_module.get_data_table(this._current_state).DefaultView;
                fields = Program.user_set._trans_table_fields;
                this.b_action_add.Enabled = true;
                this.b_edit.Enabled = true;
                this.b_search.Enabled = true;
                bn.Enabled = true;
                gw.ReadOnly = true;
                this.bindingNavigatorAddNewItem.Enabled = false;
                this.bindingNavigatorDeleteItem.Enabled = false;
                this.b_commit.Enabled = false;
                break;
                case "CustomerInterests":
                //bs.DataSource = Program.data_module.get_data_table(this._current_state).DefaultView;
                fields = Program.user_set._int_table_fields;
                this.b_action_add.Enabled = false;
                this.b_edit.Enabled = false;
                this.b_search.Enabled = false;
                bn.Enabled = true;
                gw.ReadOnly = true;
                this.bindingNavigatorAddNewItem.Enabled = false;
                this.bindingNavigatorDeleteItem.Enabled = false;
                this.b_commit.Enabled = false;
                break;
                default:
                fields = new ArrayList();
                break;
            }
            bn.BindingSource = bs;
            gw.DataSource = bs;
            gw.Update();
            this.hide_non_columns(this.gw, fields);
            this.rename_gw_columns();
            gw.Show();
            this.UpdateTitle();
        }

        private void hide_non_columns(DataGridView grid, ArrayList fields)
        {
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                grid.Columns[i].Visible = false;
            }
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                bool visible = false;
                foreach (string field in fields)
                {
                    if (grid.Columns[i].HeaderText == field)
                    {
                        visible = true;
                        break;
                    }
                }
                if (visible)
                {
                    grid.Columns[i].Visible = true;
                }
            }
        }

        private void rename_gw_columns()
        {
            for (int i = 0; i < this.gw.Columns.Count; i++)
            {
                switch (this.gw.Columns[i].HeaderText) 
                { 
                    case "CustomerID":
                    this.gw.Columns[i].HeaderText = "Код клиента";
                    break;

                    case "Name":
                    this.gw.Columns[i].HeaderText = "ФИО";
                    break;

                    case "AreaCode":
                    this.gw.Columns[i].HeaderText = "Код региона";
                    break;

                    case "HouseNumber":
                    this.gw.Columns[i].HeaderText = "Дом";
                    break;

                    case "Street":
                    this.gw.Columns[i].HeaderText = "Улица";
                    break;

                    case "City":
                    this.gw.Columns[i].HeaderText = "Город";
                    break;

                    case "Region":
                    this.gw.Columns[i].HeaderText = "Регион";
                    break;

                    case "ZipPostalCode":
                    this.gw.Columns[i].HeaderText = "Почт. индекс";
                    break;

                    case "Country":
                    this.gw.Columns[i].HeaderText = "Страна";
                    break;

                    case "Email":
                    this.gw.Columns[i].HeaderText = "Эл. почта";
                    break;

                    case "PhoneNumber":
                    this.gw.Columns[i].HeaderText = "Телефон";
                    break;

                    case "ArtistID":
                    this.gw.Columns[i].HeaderText = "Код художника";
                    break;

                    case "ArtistName":
                    this.gw.Columns[i].HeaderText = "Имя художника";
                    break;

                    case "BirthYear":
                    this.gw.Columns[i].HeaderText = "Год рождения";
                    break;

                    case "DeceaseYear":
                    this.gw.Columns[i].HeaderText = "Год смерти";
                    break;
               
                    case "Nationality":
                    this.gw.Columns[i].HeaderText = "Национальность";
                    break;

                    case "TransactionID":
                    this.gw.Columns[i].HeaderText = "Код сделки";
                    break;

                    case "WorkID":
                    this.gw.Columns[i].HeaderText = "Код работы";
                    break;

                    case "DateAcquired":
                    this.gw.Columns[i].HeaderText = "Дата приобретения";
                    break;

                    case "AcquisitionPrice":
                    this.gw.Columns[i].HeaderText = "Цена приобретения";
                    break;

                    case "PurchaseDate":
                    this.gw.Columns[i].HeaderText = "Дата продажи";
                    break;

                    case "SalesPrice":
                    this.gw.Columns[i].HeaderText = "Цена продажи";
                    break;

                    case "AskingPrice":
                    this.gw.Columns[i].HeaderText = "Заявленная цена";
                    break;

                    case "Title":
                    this.gw.Columns[i].HeaderText = "Название";
                    break;

                    case "Copy":
                    this.gw.Columns[i].HeaderText = "Копия";
                    break;

                    case "Description":
                    this.gw.Columns[i].HeaderText = "Описание";
                    break;

                    case "Customer":
                    this.gw.Columns[i].HeaderText = "Клиент";
                    break;

                    case "Artist":
                    this.gw.Columns[i].HeaderText = "Художник";
                    break;

                    case "CustomerName":
                    this.gw.Columns[i].HeaderText = "Клиент";
                    break;

                    case "CustomerPhoneNumber":
                    this.gw.Columns[i].HeaderText = "Тел. Клиента";
                    break;

                    case "WorkTitle":
                    this.gw.Columns[i].HeaderText = "Работа";
                    break;

                    case "WorkCopy":
                    this.gw.Columns[i].HeaderText = "Копия";
                    break;

                };
            }
            this.gw.Update();
        }

        private void HideAllOtherPanels()
        {
            //throw new NotImplementedException();
            //pClients.Hide();
            this.Text = "View Ridge Assistant v1.0 beta - Клиенты";
        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            about_vrdbcs about = new about_vrdbcs();
            about.ShowDialog();
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(
            "Вы действительно хотите выйти?",
            "Выход", MessageBoxButtons.YesNo,
            MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            
            this.Close();
            
        }

        private void b_commit_Click(object sender, EventArgs e)
        {
            try
            {
                this.Validate();
                this.gw.EndEdit();
                Program.data_module.apply_changes(this._current_state);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gw_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            gw.BeginEdit(true);
        }

        //Нажатие пункта подключения/отпключения базы данных
        private void connect_to_db_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            b_connect_to_db.Enabled = false; //залочим кнопку шоб не дергалсо...
            string result;  //результат попытки коннекта/дисконнекта
            //Если в данный момент не присоединены к базе, то...
            if (Program.data_module.get_connect_status() == "DISCONNECTED")
            {
                this.connect_status.Text = "Подключение к базе данных...";
                this.Update();
                result = Program.data_module.connect_to_db();
                if (!(result == "OK"))
                {
                    MessageBox.Show(result);
                    this.connect_status.Text = "Отключен от базы данных";
                    b_connect_to_db.Enabled = true;
                    this.Update();
                    return;
                }
                else
                {
                    this.connect_status.Text = "Подключен к базе данных";
                    this.EnablePanels();
                    b_connect_to_db.Enabled = true;
                    this.Update();
                    b_connect_to_db.Text = "Отключиться";
                }
            }
            else
            //Если в данный момент подключены к базе, то...
            if (Program.data_module.get_connect_status() == "CONNECTED")
            {
                this.connect_status.Text = "Отключение от базы данных...";
                this.Update();
                result = Program.data_module.disconnect_db();
                if (!(result == "OK"))
                {
                    MessageBox.Show(result);
                    this.connect_status.Text = "Подключен к базе данных";
                    b_connect_to_db.Enabled = true;
                    this.Update();
                    return;
                }
                else
                {
                    this.connect_status.Text = "Отключен от базы данных";
                    this.DisablePanels();
                    b_connect_to_db.Enabled = true;
                    this._current_state = "NONE";
                    this.b_commit.Enabled = false;
                    this.UpdateTitle();
                    this.Update();
                    b_connect_to_db.Text = "Подключиться";
                }
                //Надо как-то очищать gw (!!!)
                this.gw.Hide();
            }
            else
            //Если в данный момент идет процесс коннекта, то...
            if (Program.data_module.get_connect_status() == "PROCESS_CONNECTING")
            {
                MessageBox.Show("Идет процесс подключения, нельзя выполнить действие в данный момент");
            }
            else
            //Если в данный момент идет процесс дисконнекта, то...
            if (Program.data_module.get_connect_status() == "PROCESS_DISCONNECING")
            {
                MessageBox.Show("Идет процесс отключения, нельзя выполнить действие в данный момент");
            };
            
        }

        //Вызов настроек подключения к базе данных
        private void подключениеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            db_settings db_set = new db_settings();
            db_set.ShowDialog();
        }

        //Вызов настроек интерфейса программы и отображения таблиц
        private void интерфейсToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            gui_settings gui_set = new gui_settings(this);
            gui_set.Show();
        }

        //Нажата кнопка "добавить" на панели Действий
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            switch (this._current_state)
            {
                case "CUSTOMER": 
                    this.add_new_customer();
                    break;
                case "ARTIST":
                    this.add_new_artist();
                    break;
                case "WORK_VIEW":
                    this.add_new_work();
                    break;
                case "TRANS_VIEW":
                    this.add_new_transaction();
                    break;
            }
            this.load_data_table(this._current_state);
        }

        //Добавление новой транзакции
        public void add_new_transaction()
        {
            trans_select trans_select_form = new trans_select(Program.data_module);
            trans_select_form.ShowDialog();
            trans_select_form.Dispose();
        }

        //Добавление нового клиента
        private void add_new_customer()
        {
            //this.bindingNavigatorAddNewItem.PerformClick();
            //this.Enabled = false;
            form_customer customer = new form_customer(this, Program.data_module);
            customer.ShowDialog();
        }

        //Добавление нового хужодника
        private void add_new_artist()
        {
            //this.Enabled = false;
            form_artist artist = new form_artist(Program.data_module);
            artist.ShowDialog();
            //Запуск окна добавления нового художника
        }

        //Добавление новой картины
        private void add_new_work()
        {
            work_form work = new work_form(this, Program.data_module);
            work.ShowDialog();
        }

        public void UpdateActiveGW()
        {
            gw.Update();
        }

        private void b_edit_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(gw.Rows[gw.CurrentRow.Index].Cells[0].Value.ToString());
            switch (this._current_state)
            {
                case "CUSTOMER":
                    form_customer customer = null;
                    try
                    {
                        customer = new form_customer(this, Program.data_module, Convert.ToInt32(gw.Rows[gw.CurrentRow.Index].Cells[0].Value.ToString()));
                        customer.ShowDialog();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Выберите клиента!");
                    }
                break;

                case "ARTIST":
                form_artist artist = null;
                try
                {
                    artist = new form_artist(Program.data_module, Convert.ToInt32(gw.Rows[gw.CurrentRow.Index].Cells[0].Value.ToString()));
                    artist.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Выберите художника!");
                }
                break;

                case "WORK_VIEW":
                //this.Enabled = false;
                work_form work = null;
                    try
                {
                    work = new work_form(this, Program.data_module, Convert.ToInt32(gw.Rows[gw.CurrentRow.Index].Cells[0].Value.ToString()));
                    work.ShowDialog();
                }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Выберите работу!");
                    }
                break;

                case "TRANS_VIEW":
                form_transaction transaction = null;
                try
                {
                    transaction = new form_transaction(Program.data_module, Convert.ToInt32(gw.Rows[gw.CurrentRow.Index].Cells[0].Value.ToString()));
                    transaction.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Выберите транзакцию!");
                }
                break;
            }
            this.load_data_table(this._current_state);
        }
       
        //Выбор параметров поиска в активном GridView
        private void b_search_Click(object sender, EventArgs e)
        {
            if (this._search_act)
            {
                this.p_search.Hide();
                this._search_act = false;
            }
            else
            {
                this._search_act = true;
                this.b_commit.Enabled = false;
                //this.b_edit.Enabled = false;
                this.bindingNavigatorAddNewItem.Enabled = false;
                this.bindingNavigatorDeleteItem.Enabled = false;
                this.tabs_search.SelectedIndex = 0;

                this.update_customer_city_list();
                this.update_customer_country_list();
                this.update_customer_name_list();
                this.update_artist_name_list();
                this.update_artist_nat_list();
                this.update_work_title_list();
                this.update_work_copy_list();
                this.update_work_artist_list();

                switch (this._current_state)
                {
                    case "CUSTOMER":
                        this.tabs_search.SelectedIndex = 0;
                        //this.ToolClients_Click(sender, e);
                        break;
                    case "ARTIST":
                        this.tabs_search.SelectedIndex = 2;
                        //this.ToolArtists_Click(sender, e);
                        break;
                    case "WORK_VIEW":
                        this.tabs_search.SelectedIndex = 1;
                        //this.ToolWorks_Click(sender, e);
                        break;
                }
                this.p_search.Visible = true;
                this.p_search.Show();
            }
        }

        //Обновление комбо-бокса с городами клиентов для поиска
        private void update_customer_city_list()
        {
            ArrayList customer_city;
            customer_city = Program.data_module.get_list_by_table_and_column("CUSTOMER", "City");
            if (customer_city != null)
            {
                this.combo_customer_city.Items.Clear();
                foreach (string city in customer_city)
                {
                    this.combo_customer_city.Items.Add(city);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список городов");
            }
        }

        //Обновление комбо-бокса со странами клиентов для поиска
        private void update_customer_country_list()
        {
            ArrayList customer_country;
            customer_country = Program.data_module.get_list_by_table_and_column("CUSTOMER", "Country");
            if (customer_country != null)
            {
                this.combo_customer_country.Items.Clear();
                foreach (string country in customer_country)
                {
                    this.combo_customer_country.Items.Add(country);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список стран");
            }
        }

        //Обновление комбо-бокса с именами клиентов для поиска
        private void update_customer_name_list()
        {
            ArrayList customer_name;
            customer_name = Program.data_module.get_list_by_table_and_column("CUSTOMER", "Name");
            if (customer_name != null)
            {
                this.combo_customer_name.Items.Clear();
                foreach (string name in customer_name)
                {
                    this.combo_customer_name.Items.Add(name);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список имен клиентов");
            }
        }

        //Обновление комбо-бокса с именами художников для поиска
        private void update_artist_name_list()
        {
            ArrayList artist_name;
            artist_name = Program.data_module.get_list_by_table_and_column("ARTIST", "Name");
            if (artist_name != null)
            {
                this.combo_artist_name.Items.Clear();
                foreach (string name in artist_name)
                {
                    this.combo_artist_name.Items.Add(name);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список имен художников");
            }
        }

        //Обновление комбо-бокса с именами художников (в картинах) для поиска
        private void update_work_artist_list()
        {
            ArrayList work_artist;
            work_artist = Program.data_module.get_list_by_table_and_column("ARTIST", "Name");
            if (work_artist != null)
            {
                this.combo_work_artist_name.Items.Clear();
                foreach (string name in work_artist)
                {
                    this.combo_work_artist_name.Items.Add(name);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список имен художников");
            }
        }

        //Обновление комбо-бокса с названиями картин
        private void update_work_title_list()
        {
            ArrayList work_title;
            work_title = Program.data_module.get_list_by_table_and_column("WORK", "Title");
            if (work_title != null)
            {
                this.combo_work_title.Items.Clear();
                foreach (string name in work_title)
                {
                    this.combo_work_title.Items.Add(name);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список названий картин");
            }
        }

        //Обновление комбо-бокса с национальностями художников
        private void update_artist_nat_list()
        {
            ArrayList artist_nat;
            artist_nat = Program.data_module.get_list_by_table_and_column("ARTIST", "Nationality");
            if (artist_nat != null)
            {
                this.combo_artist_nat.Items.Clear();
                foreach (string name in artist_nat)
                {
                    this.combo_artist_nat.Items.Add(name);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список названий картин");
            }
        }

        //Обновление комбо-бокса с номерами копий картин
        private void update_work_copy_list()
        {
            ArrayList work_copy;
            work_copy = Program.data_module.get_list_by_table_and_column("WORK", "Copy");
            if (work_copy != null)
            {
                this.combo_work_copy.Items.Clear();
                foreach (string name in work_copy)
                {
                    this.combo_work_copy.Items.Add(name);
                }
            }
            else
            {
                MessageBox.Show("Не удалось получить список номеров копий картин");
            }
        }

        private void b_start_customer_search_Click(object sender, EventArgs e)
        {
            this.search_customers();
        }

        private void start_works_search()
        {
            this._current_state = "WORK_VIEW";
            this.UpdateTitle();
            gw.Hide();
            gw.DataSource = null;
            bn.BindingSource = null;
            bs.DataSource = null;

            DataTable find_works_table;// = null;
            find_works_table = Program.data_module.get_works_by_param(
                                                      this.cb_work_title.Checked,
                                                      this.cb_work_copy.Checked,
                                                      this.cb_work_artist_name.Checked,
                                                      this.cb_work_description.Checked,
                                                      this.combo_work_title.Text,
                                                      this.combo_work_copy.Text,
                                                      this.combo_work_artist_name.Text,
                                                      this.combo_work_desc.Text);
            if (find_works_table != null)
            {
                bs.DataSource = find_works_table.DefaultView;
                bn.BindingSource = bs;
                gw.DataSource = bs;
                this.hide_non_columns(this.gw, Program.user_set._work_table_fields);
                this.rename_gw_columns();
                gw.Update();
                gw.Show();
            }
            else
            {
                MessageBox.Show("Не удалось произвести поиск клиентов");
            }
        }

        private void search_customers()
        {
            this._current_state = "CUSTOMER";
            this.UpdateTitle();
            gw.Hide();
            gw.DataSource = null;
            bn.BindingSource = null;
            bs.DataSource = null;

            DataTable find_customers_table;// = null;
            find_customers_table = Program.data_module.get_customers_table_by_param(
                                                      this.cb_customer_name.Checked,
                                                      this.cb_customer_city.Checked,
                                                      this.cb_customer_country.Checked,
                                                      this.cb_customer_transactions.Checked,
                                                      this.combo_customer_name.Text,
                                                      this.combo_customer_city.Text,
                                                      this.combo_customer_country.Text,
                                                      Convert.ToInt32(this.num_customer_start_trans.Value),
                                                      Convert.ToInt32(this.num_customer_end_trans.Value));
            if (find_customers_table != null)
            {
                bs.DataSource = find_customers_table.DefaultView;
                bn.BindingSource = bs;
                gw.DataSource = bs;
                this.hide_non_columns(this.gw, Program.user_set._customer_table_fields);
                this.rename_gw_columns();
                gw.Update();
                gw.Show();
            }
            else
            {
                MessageBox.Show("Не удалось произвести поиск клиентов");
            }
        }

        private void b_start_artist_search_Click(object sender, EventArgs e)
        {
            this.search_artist();   
        }

        private void search_artist()
        {
            this._current_state = "ARTIST";
            this.UpdateTitle();
            gw.Hide();
            DataTable find_artists_table;
            find_artists_table = Program.data_module.get_artists_by_param(this.cb_name.Checked,
                                                   this.cb_nat.Checked,
                                                   this.cb_bd_date.Checked,
                                                   this.cb_dd_date.Checked,
                                                   this.combo_artist_name.Text,
                                                   this.combo_artist_nat.Text,
                                                   Convert.ToInt32(this.num_start_bd_date.Value),
                                                   Convert.ToInt32(this.num_end_bd_date.Value),
                                                   Convert.ToInt32(this.num_start_dd_date.Value),
                                                   Convert.ToInt32(this.num_end_dd_date.Value));
            if (find_artists_table != null)
            {
                bs.DataSource = find_artists_table.DefaultView;
                bn.BindingSource = bs;
                gw.DataSource = bs;
                this.hide_non_columns(this.gw, Program.user_set._artist_table_fields);
                this.rename_gw_columns();
                gw.Update();
                gw.Show();
            }
            else
            {
                MessageBox.Show("Не удалось произвести поиск клиентов");
            }
        }

        private void b_close_search_Click(object sender, EventArgs e)
        {
           
        }

        private void gw_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void Tools_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void ToolReports_Click(object sender, EventArgs e)
        {
           
        }

        private void client_tab_search_click(object sender, EventArgs e)
        {
            this.update_customer_city_list();
            this.update_customer_country_list();
            this.update_customer_name_list();
        }

        private void mi_create_custom_report_Click(object sender, EventArgs e)
        {
            reports new_report = new reports();
            new_report.Show();
        }

        private void b_print_Click(object sender, EventArgs e)
        {
            //this.gw.
            MessageBox.Show("Вывод на печать таблицы недоступен в текущей версии.");
        }

        private void tabpage_artists_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("yapp!");
        }

        private void Menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void most_sales_artists_Click(object sender, EventArgs e)
        {
            //this.StatusLabel.Text = "Генерация отчета";
            //ReportGenerator rep_gen = new ReportGenerator(Program.data_module, "MOST_SALES_ARTISTS", 0);
        }

        private void mi_tables_panel_Click(object sender, EventArgs e)
        {
            if (mi_tables_panel.Checked)
            {
                this.Tools.Show();
            }
            else
            {
                this.Tools.Hide();
            }
            Program.user_set._main_gui._show_tables_panel = mi_tables_panel.Checked;
        }

        private void mi_actions_panel_Click(object sender, EventArgs e)
        {
            if (mi_actions_panel.Checked)
            {
                this.Actions.Show();
                //mi_tables_panel.Checked = false;
            }
            else
            {
                this.Actions.Hide();
                //mi_tables_panel.Checked = true;
            }
            Program.user_set._main_gui._show_actions_panel = mi_actions_panel.Checked;
        }

        private void mi_gridcontrol_panel_Click(object sender, EventArgs e)
        {
            if (mi_gridcontrol_panel.Checked)
            {
                this.bn.Show();
            }
            else
            {
                this.bn.Hide();
            }
            Program.user_set._main_gui._show_gridcontrol_panel = mi_gridcontrol_panel.Checked;
        }

        private void main_Load(object sender, EventArgs e)
        {
            db_settings db_set = new db_settings();
            db_set.ShowDialog();
            db_set.Dispose();
        }

        private void mi_exp_db_Click(object sender, EventArgs e)
        {
            
        }

        private void mi_imp_db_Click(object sender, EventArgs e)
        {
            String trans_code = "";
            OpenFileDialog ofDialog = new OpenFileDialog();
            ofDialog.Filter = "SQL-Queries files|*.sql";
            ofDialog.Title = "Выберите файл, содержащий базу данных:";
            if (ofDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(ofDialog.FileName);
                //MessageBox.Show(sr.ReadToEnd());
                trans_code = sr.ReadToEnd();
                trans_code = "BEGIN TRANSACTION\n\n" + trans_code;
                trans_code = trans_code + "\nIF @@ERROR<>0 ROLLBACK TRANSACTION\nELSE COMMIT TRANSACTION\n"; 
                string result = Program.data_module.execute_string_query(trans_code);
                MessageBox.Show(trans_code);
                if (result == "OK")
                {
                    MessageBox.Show("Импорт базы данных успешно завершен!");
                }
                else
                {
                    MessageBox.Show("Ошибка при импортировании данных из файла в базу данных: " + result);
                }
                sr.Close();
            } 
            ofDialog.Dispose();
        }

        private void mi_sales_works_list_Click(object sender, EventArgs e)
        {
            ReportGenerator rep_gen = new ReportGenerator(Program.data_module, "WORKS_IN_GALLERY", 0);
        }

        private void базаДанныхToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Program.user_set.saveSettingsToFile();
        }

        private void mi_sql_console_Click(object sender, EventArgs e)
        {
            sql_console sql_con = new sql_console(Program.data_module);
            sql_con.ShowDialog();
            sql_con.Dispose();
        }

        private void b_start_works_search_Click(object sender, EventArgs e)
        {
            this.start_works_search();
        }

        private void mi_purchasing_dynamics_Click(object sender, EventArgs e)
        {
            graphics gr = new graphics(Program.data_module);
            gr.ShowDialog();
            gr.Dispose();
        }

        private void main_Shown(object sender, EventArgs e)
        {
            db_settings db_set = new db_settings();
            db_set.ShowDialog();
            db_set.Dispose();
        }




    }

}
